<template>
  <div class="cret-editor">
<!--    @click="closeEditor()"-->
    <el-dialog
      append-to-body
      width="1000px"
      title="证件详情"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form label-width="120px" :model="certForm" ref="certForm" :rules="certFormRules">
        <el-row v-if="showUserSelector">
          <el-col :span="11">
            <el-form-item label="人员" prop="userId">
              <el-select
                style="width:100%"
                v-model="certForm.userId"
                filterable
                remote
                placeholder="请输入姓名"
                :remote-method="searchUser"
                :loading="loading"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.realname + ' | ' + item.identityCard"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="证件类型" prop="certType">
              <div v-if="readonly">{{certForm.certType}}</div>
              <el-select
                v-else
                filterable
                v-model="certForm.certType"
                placeholder="请选择证件类型"
                style="width:100%"
                @change="certTypeChanged"
              >
                <el-option
                  v-for="item in certTypeList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="证件名称" prop="certName">
              <div v-if="readonly">{{certForm.certName}}</div>
              <el-select
                v-else
                filterable
                v-model="certForm.certName"
                placeholder="请选择证件类型"
                style="width:100%"
              >
                <el-option v-for="item in certNameList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="证件编号" prop="certNumber">
              <div v-if="readonly">{{certForm.certNumber}}</div>
              <el-input v-else v-model="certForm.certNumber" />
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="发证时间" prop="certOpenDate">
              <div v-if="readonly">{{certForm.certOpenDate}}</div>
              <el-date-picker
                style="width:100%"
                v-else
                v-model="certForm.certOpenDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择发证时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="专业类型" prop="specialty">
              <div v-if="readonly">{{certForm.specialty}}</div>
              <el-input v-else v-model="certForm.specialty" />
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="专业级别" prop="level">
              <div v-if="readonly">{{certForm.level}}</div>
              <el-input v-else v-model="certForm.level" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="技术等级" prop="skillLevel">
              <div v-if="readonly">{{certForm.skillLevel}}</div>
              <el-input v-else v-model="certForm.skillLevel" />
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="证件工种" prop="craft">
              <div v-if="readonly">{{certForm.craft}}</div>
              <el-input v-else v-model="certForm.craft" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="有效期" prop="dateRange">
              <div
                v-if="readonly && certForm.dateRange"
              >{{certForm.certStartTime + ' - ' + certForm.certEndTime}}</div>
              <el-date-picker
                v-else
                v-model="certForm.dateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="复审时间" prop="certSecondTime">
              <div v-if="readonly">{{certForm.certSecondTime}}</div>
              <el-date-picker
                style="width:100%"
                v-else
                v-model="certForm.certSecondTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择复审时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="发证机构" prop="certAuthority">
              <div v-if="readonly">{{certForm.certAuthority}}</div>
              <el-input v-else v-model="certForm.certAuthority"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="操作项目" prop="remark">
              <div v-if="readonly">{{certForm.remark}}</div>
              <el-input v-else v-model="certForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="正面照" prop="photoZ">
              <div style="display: flex;width: 160px">
                <div>
                  <img
                    style="borderRadius:5px"
                    v-if="readonly"
                    width="100"
                    height="100"
                    :src="certForm.photoZ"
                  />
                  <avatar-uploader
                    v-else
                    :avatar="certForm.photoZ"
                    @uploaded="photoZUploaded"
                  ></avatar-uploader>
                </div>
                <div>
                  <img v-if="certForm.photoZ" style="width: 26px;height: 26px;margin-top: 90px" src="static/img/user/fdj.png" @click="big(1)"/>
                </div>
              </div>
<!--              <el-upload-->
<!--                class="avatar-uploader"-->
<!--                :action="action"-->
<!--                list-type="picture-card"-->
<!--                :file-list="fileList"-->
<!--                :on-preview="Preview"-->
<!--                :on-success="handlePictureCardPreview">-->
<!--                <i class="el-icon-plus"></i>-->
<!--              </el-upload>-->
            </el-form-item>
            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img width="100%" :src="certForm.photoZ" alt="">
            </el-dialog>
          </el-col>

          <el-col :span="11" :offset="1">
            <el-form-item label="反面照" prop="photoF">
              <div style="display: flex;width: 160px">
                <div>
                  <img
                    style="borderRadius:5px"
                    v-if="readonly"
                    width="100"
                    height="100"
                    :src="certForm.photoF"
                  />
                  <avatar-uploader  v-else :avatar="certForm.photoF" @uploaded="photoFUploaded" />
                </div>
                <div>
                  <img v-if="certForm.photoF" style="width: 26px;height: 26px;margin-top: 90px" src="static/img/user/fdj.png" @click="big(2)"/>
                </div>
              </div>
<!--              <div class="notice">图片仅支持“.jpg,.jpeg,.png,.gif”，不可大于4M。</div>-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-dialog
        width="40%"
        :visible.sync="amplification"
        append-to-body>
        <div>
          <img v-if="this.fangbig === 1" style="width: 100%;height: 800px" :src="certForm.photoZ" />
          <img v-if="this.fangbig === 2"style="width: 100%;height: 800px" :src="certForm.photoF" />
        </div>
      </el-dialog>
      <div slot="footer">
        <el-button v-if="readonly" @click="close()" type="primary">确认</el-button>
        <el-button v-if="!readonly" @click="close()">取消</el-button>
        <el-button v-if="!readonly" type="primary" @click="save()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AvatarUploader from '../../../components/uploader/avatar-uploader'
// import Vue from 'vue'
export default {
  name: 'certEditor',
  components: {
    AvatarUploader
  },
  data() {
    return {
      certNameList: [],
      userList: [],
      userOptions: [],
      fileList: [],
      loading: false,
      action: '',
      certForm: {
        isView: false,
        isEdit: false,
        userId: '',
        craft: '',
        certName: '',
        certType: '',
        certNumber: '',
        certAuthority: '',
        certStartTime: '',
        certEndTime: '',
        certOpenDate: '',
        certSecondTime: '',
        remark: '',
        specialty: '',
        level: '',
        skillLevel: '',
        photoZ: '',
        photoF: '',
        dateRange: []
      },
      fangbig: null,
      visible: false,
      readonly: false,
      amplification: false,
      showUserSelector: true,
      dialogVisible: false,
      certFormRules: {
        userId: [
          { required: true, message: '用户ID不能为空', trigger: 'blur' }
        ],
        certName: [
          { required: true, message: '请填写证件名称', trigger: 'blur' }
        ],
        certType: [
          { required: true, message: '请填写证件类型', tirgger: 'blur' }
        ]
      }
    }
  },
  methods: {
    big(val) {
      this.fangbig = val
      this.amplification = true
    },
    open({ id, readonly, userId = null }) {
      this.readonly = readonly
      this.visible = true
      this.$nextTick(async () => {
        this.$refs.certForm.resetFields()
        if (id) {
          await this.buildForm(id)
          this.showUserSelector = false
          this.certTypeChanged(this.certForm.certType)
        } else {
          this.certForm.isEdit = false
          this.certForm.userId = userId
          this.showUserSelector = !userId
        }
      })
    },
    handlePictureCardPreview(file) {
      console.log(file)
      this.certForm.photoZ = file.url
    },
    Preview(file) {
      this.dialogVisible = true
    },
    close() {
      this.visible = false
    },
    certTypeChanged(val) {
      var certType = this.certTypeList.find(x => x.label === val)
      if (certType.remarks) {
        this.certNameList = certType.remarks.split(',')
      } else {
        this.certNameList = []
      }
    },
    async searchUser(keyword) {
      if (keyword !== '') {
        this.loading = true
        setTimeout(async () => {
          this.loading = false
          var userList = await this.getSearchUserList()
          this.userOptions = userList.filter(
            x => x.realname.indexOf(keyword) > -1
          )
        }, 200)
      }
    },
    async getSearchUserList() {
      if (this.userList.length === 0) {
        var url = '/usercenter-admin/user/getSimpleUserInfoList'
        let result = await this.$http.post(url)
        this.userList = result.data
      }
      return this.userList
    },
    photoFUploaded(file) {
      this.certForm.photoF = file.url
    },
    photoZUploaded(file) {
      console.log(file)
      this.certForm.photoZ = file.url
    },
    async buildForm(id) {
      let res = await this.$http.post('/usercenter-admin/certManage/info/' + id)
      let cert = res.data
      this.certForm.id = cert.id
      this.certForm.isEdit = true
      this.certForm.userId = cert.userId
      this.certForm.craft = cert.craft
      this.certForm.level = cert.level
      this.certForm.certName = cert.certName
      this.certForm.certType = cert.certType
      this.certForm.certNumber = cert.certNumber
      this.certForm.certAuthority = cert.certAuthority
      this.certForm.certStartTime = cert.certStartTime
      this.certForm.certEndTime = cert.certEndTime
      this.certForm.certOpenDate = cert.certOpenDate
      this.certForm.certSecondTime = cert.certSecondTime
      this.certForm.remark = cert.remark
      this.certForm.specialty = cert.specialty
      this.certForm.skillLevel = cert.skillLevel
      this.certForm.photoZ = cert.photoZ
      this.certForm.photoF = cert.photoF

      // 起始时间初始化
      this.certForm.dateRange = [
        cert.certStartTime || '',
        cert.certEndTime || ''
      ]
    },
    buildRequest() {
      let request = JSON.parse(JSON.stringify(this.certForm))
      request['certStartTimeStr'] = request.certStartTime
      request['certEndTimeStr'] = request.certEndTime
      request['certOpenDateStr'] = request.certOpenDate
      request['certSecondTimeStr'] = request.certSecondTime
      delete request.certStartTime
      delete request.certEndTime
      delete request.certOpenDate
      delete request.certSecondTime
      delete request.dateRange
      return request
    },
    async save() {
      let valid = await this.$refs.certForm.validate()
      if (!valid) return

      let res = await this.$http({
        method: 'post',
        url: this.$http.adornUrl(
          `/usercenter-admin/certManage/${
            this.certForm.isEdit ? 'update' : 'save'
          }`
        ),
        data: this.buildRequest()
      })

      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '保存人员证件成功' })
        this.close()
        this.$store.dispatch('user/loadAlertListCount')
        this.$emit('refresh')
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    }
  },
  watch: {
    'certForm.dateRange'(val) {
      if (val && val.length > 1) {
        this.certForm.certStartTime = val[0]
        this.certForm.certEndTime = val[1]
      } else {
        this.certForm.certStartTime = ''
        this.certForm.certEndTime = ''
      }
    }
  },
  computed: {
    certTypeList() {
      return this.$store.getters['user/certTypeList']
    }
  },
  created() {
    this.$store.dispatch('user/loadCertTypeList')
  }
}
</script>

<style>
</style>
